package com.houserent.service;

import com.houserent.domain.House;
import com.houserent.utils.Utility;

public class HouseService {
    private House[] houses;
    private  int counterid=1;
    private  int housenums=1;
    public HouseService(int size) {
        houses = new House[size];
        houses[0]=new House(1,"jack","112","海淀区",2000,"未出租");
    }
    //modify方法，按照Id找到并修改一个房屋信息
    public boolean modifyHouse(int modId) {
        int index=-1;
        for(int i=0;i<housenums;i++) {
            if(houses[i].getId()==modId) {
                index=i;
                break;
            }
        }
        if(index==-1) {
            return false;
        }
        System.out.println("=================修改房屋=============");
        System.out.print("姓名("+houses[index].getName()+"): ");
        String name = Utility.readString(8,"");
        if(!"".equals(name)) {
            houses[index].setName(name);
        }
        System.out.print("电话("+houses[index].getPhone()+"): ");
        String phone =Utility.readString(11,"");
        if(!"".equals(phone)) {
            houses[index].setPhone(phone);
        }
        System.out.print("地址("+houses[index].getAddress()+"): ");
        String address =Utility.readString(16,"");
        if(!"".equals(address)){
                houses[index].setAddress(address);
        }
        System.out.print("月租("+houses[index].getRent()+"): ");
        int rent =Utility.readInt(-1);
        if(rent!=-1)
            houses[index].setRent(rent);
        System.out.print("状态("+houses[index].getState()+"): ");
        String state =Utility.readString(3,"");
        if(!"".equals(state)) {
            houses[index].setState(state);
        }
        return true;
    }
    //search方法，按照Id查找一个房屋信息
    public boolean search (int searchId){
        int index=-1;
        for(int i=0;i<housenums;i++) {
            if(houses[i].getId()==searchId) {
                index=i;
                break;
            }
        }
        if(index==-1) {
            return false;
        }
        System.out.println(houses[index].toString());
        return true;
    }
    //del方法，删除一个房屋信息
    public boolean del(int delId) {
        int index=-1;
        for(int i=0;i<housenums;i++) {
            if(houses[i].getId()==delId) {
                index=i;
                break;
            }
        }
        if(index==-1) {
            return false;
        }
        for(int i=index;i<houses.length-1;i++) {
            houses[i]=houses[i+1];
        }
        houses[--housenums]=null;
        return true;
    }
    //add方法，添加新对象，返回boolean
    public boolean add(House newhouse){
        if(housenums==houses.length){
            System.out.println("数组已满，不能再添加了...");
            return false;
        }
        newhouse.setId(++counterid);
        //新增一个房屋
        houses[housenums++]=newhouse;
        return true;
    }

    public House[] list() {
        return houses;
    }
}
